/*
 * @Author: xuetao 3168581151@qq.com
 * @Date: 2025-01-27
 * @LastEditors: xuetao 3168581151@qq.com
 * @LastEditTime: 2025-03-15
 * @Description: 
 */
import 'package:chat_client/enums/chat_enum.dart';
import 'package:chat_client/utils/date_formater.dart' show getTimestamp;
import 'package:hive/hive.dart';

part 'conversation_model.g.dart'; // 引入生成的.g.dart文件

@HiveType(typeId: 5)
class Conversation {
  @HiveField(0)
  final String conversationId; // 会话id

  @HiveField(1)
  final int type; // 会话类型, 单聊/群聊

  @HiveField(2)
  final List<String> messages; // 会话消息列表 -》会话查找消息 -》关联消息

  @HiveField(3)
  String? lastMessage; // 最后一条消息的内容

  @HiveField(4)
  int lastActive; // 最后会话时间

  @HiveField(5)
  final String? pivateId; // 单聊专属（储存单聊对象的userId）

  @HiveField(6)
  final String? groupId; // 群聊专属

  @HiveField(7)
  final String avatarUrl; //

  @HiveField(8)
  final String nickname; //

  Conversation({
    required this.conversationId,
    required this.type,
    required this.messages,
    this.lastMessage,
    required this.lastActive,
    this.pivateId,
    this.groupId,
    required this.avatarUrl,
    required this.nickname,
  });

  // 安全提取 sender 对象

  factory Conversation.fromJson(Map<String, dynamic> json) {
    final messages = _safeGetList(json, 'messages');
    return Conversation(
      conversationId: json['_id'] ?? '',
      type: json['type'] ?? ConversationType.user.value,
      messages: messages,
      lastMessage: json['lastMessage'] ?? '',
      lastActive: json['lastActive'] ?? getTimestamp(),
      pivateId: json['pivateId'] as String?,
      groupId: json['groupId'] as String?,
      avatarUrl: json['avatarUrl'] ?? '',
      nickname: json['nickname'] ?? '',
    );
  }

  // 增加消息
  Conversation addMessage(Message newMessage) {
    final updatedMessages = List<String>.from(messages)
      ..add(newMessage.messageId);
    return copyWith(
      messages: updatedMessages,
      lastMessage: newMessage.data,
      lastActive: newMessage.sentAt,
    );
  }

  Conversation copyWith({
    List<String>? messages,
    String? lastMessage,
    int? lastActive,
    String? conversationId,
  }) =>
      Conversation(
        messages: messages ?? this.messages,
        lastMessage: lastMessage ?? this.lastMessage,
        lastActive: lastActive ?? this.lastActive,
        conversationId: conversationId ?? this.conversationId,
        type: type,
        avatarUrl: avatarUrl,
        nickname: nickname,
        pivateId: pivateId,
        groupId: groupId,
      );

  // 安全获取 List 方法
  static List<String> _safeGetList(Map<String, dynamic> json, String key) {
    final value = json[key];
    return (value is List) ? value.cast<String>() : [];
  }

  @override
  String toString() =>
      'Conversation(type:$type,pivateId: $pivateId, groupId: $groupId)';
}

// 定义 Message 类，存储与该联系人/群组有关的所有聊天信息
@HiveType(typeId: 6)
class Message {
  @HiveField(0)
  final String? conversationId; // 会话id

  @HiveField(1)
  final String? senderId; // null为系统时间信息

  @HiveField(2)
  final String? senderAvatar;

  @HiveField(3)
  final String? senderNickname;

  @HiveField(4)
  final String messageId; // 消息Id

  @HiveField(5)
  final String data; // 消息数据内容

  @HiveField(6)
  final int type; // 消息类型

  @HiveField(7)
  final String? additional; // 附加消息

  @HiveField(8)
  final int sentAt; // 发送时间

  Message({
    required this.conversationId,
    required this.messageId,
    required this.data,
    this.additional,
    required this.type,
    required this.sentAt,
    this.senderId,
    this.senderAvatar,
    this.senderNickname,
  });

  factory Message.fromJson(Map<String, dynamic> json) {
    // 安全提取 sender 对象
    final sender = _safeGetMap(json, 'sender');
    return Message(
      conversationId: json['conversationId'] as String?,
      messageId: json['messageId'] ?? json['_id'] ?? '',
      data: json['data'] ?? '',
      type: json['type'] ?? ContentType.text.value,
      additional: json['additional'] as String?,
      sentAt: json['sentAt'] ?? getTimestamp(),
      senderId: _safeGetString(sender, '_id'),
      senderNickname: _safeGetString(sender, 'nickname'),
      senderAvatar: _safeGetString(sender, 'avatarUrl'),
    );
  }

  // 通用安全获取 Map 方法
  static Map<String, dynamic>? _safeGetMap(
      Map<String, dynamic> json, String key) {
    final value = json[key];
    return (value is Map<String, dynamic>) ? value : null;
  }

  // 通用安全获取 String 方法
  static String? _safeGetString(Map<String, dynamic>? map, String key) {
    final value = map?[key];
    return (value is String) ? value : null;
  }

  @override
  String toString() {
    return 'data:$data, senderId:$senderId, senderAvatar:$senderAvatar, senderNickname:$senderNickname';
  }
}

class ConversationPull {
  final String sessionObject;
  final String sessionType;
  final int? page;
  final int? pageSize;

  ConversationPull({
    required this.sessionObject,
    required this.sessionType,
    this.page,
    this.pageSize,
  });

  // 转换为 Map（自动过滤空字段）
  Map<String, dynamic> toMap() {
    return {
      'sessionObject': sessionObject,
      'sessionType': sessionType,
      if (page != null) 'page': page,
      if (pageSize != null) 'pageSize': pageSize,
    };
  }
}
